import requests
import json

app_id = "62c5371b-d7a7-4642-a90e-c037c848d325"
Bearer = "bce-v3/ALTAK-KdhOgoyr12pLulh5mP0Af/fd186e7ab6bf9a6558d0e1158213d432fb04afa5"

def chatWithAI(query):
    conversation_id = CreateSession()
    return Chat(conversation_id, query)

def CreateSession():
    url = "https://qianfan.baidubce.com/v2/app/conversation"

    payload = json.dumps({
        "app_id": app_id
    })
    headers = {
        'Content-Type': 'application/json',
        'X-Appbuilder-Authorization': 'Bearer ' + Bearer
    }

    response = requests.request("POST", url, headers=headers, data=payload)
    response_json = response.json()

    return response_json['conversation_id']
    # print(response_json)

def Chat(conversation_id, query):
    url = "https://qianfan.baidubce.com/v2/app/conversation/runs"

    payload = json.dumps({
        "app_id": "62c5371b-d7a7-4642-a90e-c037c848d325",
        "query": query,
        "stream": False,
        "conversation_id": conversation_id
    })
    headers = {
        'Content-Type': 'application/json',
        'X-Appbuilder-Authorization': 'Bearer ' + Bearer
    }

    response = requests.request("POST", url, headers=headers, data=payload)
    data = json.loads(response.text)

    return data['answer']
    #print(data['answer'])

